package com.chuangjian.hire.media.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.kisso.annotation.Login;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chuangjian.hire.common.controller.BaseController;
import com.chuangjian.hire.common.dto.IdsDTO;
import com.chuangjian.hire.common.dto.R;
import com.chuangjian.hire.common.exceptionEnum.ApiExceptionEnum;
import com.chuangjian.hire.common.exption.ApiException;
import com.chuangjian.hire.media.dao.MediaItemMapper;
import com.chuangjian.hire.media.dao.MediaRelateMapper;
import com.chuangjian.hire.media.domain.MediaItemDO;
import com.chuangjian.hire.media.domain.MediaRelateDO;
import com.chuangjian.hire.media.dto.*;
import com.chuangjian.hire.util.BeanUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Api(tags = "项目")
@RestController
@RequestMapping("/mediaItem")
public class MediaItemController extends BaseController {

    @Resource
    private MediaItemMapper mediaItemMapper;

    @Resource
    private MediaRelateMapper mediaRelateMapper;

    public static String baseUrl = "https://interlib.s3.ap-southeast-1.amazonaws.com/";


    @PostMapping("pageList")
    @ApiOperation("获取列表")
    public R<Page<MediaItemDTO>> pageList(Page page, @RequestBody MediaFilterDTO media) {

        Page pageResult = pageList2(page, media);

        List<MediaItemDO> records = pageResult.getRecords();

        if (CollectionUtil.isEmpty(records)) {
            return R.success(pageResult);
        }
        List<Long> pidList = records.stream().map(it -> it.getId()).collect(Collectors.toList());


        List<MediaRelateDO> mediaRelateDOS = mediaRelateMapper.selectList(Wrappers.lambdaQuery(MediaRelateDO.class)
                .in(MediaRelateDO::getPid, pidList));
        Map<Long, List<MediaRelateDO>> mediaRelateMap = mediaRelateDOS.stream().collect(Collectors.groupingBy(MediaRelateDO::getPid));


        List<MediaItemDTO> recordList = records.stream().map(it -> {
            MediaItemDTO transform = BeanUtils.transform(MediaItemDTO.class, it);

            List<MediaRelateDO> mediaRelateList = mediaRelateMap.getOrDefault(transform.getId(), new ArrayList<>());
            transform.setStillsList(mediaRelateList.stream()
                    .sorted(Comparator.comparingInt(MediaRelateDO::getSor))
                    .filter(t -> Objects.equals(t.getType(), "剧照"))
                    .map(i -> {
                        MediaRelateDTO t = BeanUtils.transform(MediaRelateDTO.class, i);
                        t.setTmpUrl(baseUrl + i.getUrl());
                        return t;
                    }).collect(Collectors.toList()));

            transform.setPosterList(mediaRelateList.stream()
                    .sorted(Comparator.comparingInt(MediaRelateDO::getSor))
                    .filter(t -> Objects.equals(t.getType(), "海报"))
                    .map(i -> {
                        MediaRelateDTO t = BeanUtils.transform(MediaRelateDTO.class, i);
                        t.setTmpUrl(baseUrl + i.getUrl());
                        return t;
                    }).collect(Collectors.toList()));

            transform.setNewsList(mediaRelateList.stream()
                    .sorted(Comparator.comparingInt(MediaRelateDO::getSor))
                    .filter(t -> Objects.equals(t.getType(), "新闻"))
                    .map(i -> {
                        MediaRelateDTO t = BeanUtils.transform(MediaRelateDTO.class, i);
                        t.setTmpUrl(baseUrl + i.getUrl());
                        return t;
                    }).collect(Collectors.toList()));

            transform.setTrailersList(mediaRelateList.stream()
                    .sorted(Comparator.comparingInt(MediaRelateDO::getSor))
                    .filter(t -> Objects.equals(t.getType(), "预告片") || Objects.equals(t.getType(), "片段") || Objects.equals(t.getType(), "花絮"))
                    .map(i -> {
                        MediaRelateDTO t = BeanUtils.transform(MediaRelateDTO.class, i);
                        t.setTmpUrl(baseUrl + i.getUrl());
                        return t;
                    }).collect(Collectors.toList()));

            transform.setMainPicUrl(baseUrl + transform.getMainPic());

            return transform;
        }).collect(Collectors.toList());

        pageResult.setRecords(recordList);


        return R.success(pageResult);
    }

    public Page<MediaItemDTO> pageList2(Page page, @RequestBody MediaFilterDTO media) {

        String endYear = null;
        if (StringUtils.isNotBlank(media.getYearOfProductionEnd())) {
            endYear = String.valueOf(Integer.parseInt(media.getYearOfProductionEnd()) + 1);
        }

        Page pageResult = mediaItemMapper.selectPage(page,
                Wrappers.lambdaQuery(MediaItemDO.class)
                        .isNull(MediaItemDO::getPid)
                        .like(StringUtils.isNotBlank(media.getProjectName()), MediaItemDO::getProjectName, media.getProjectName())
                        .ge(StringUtils.isNotBlank(media.getYearOfProductionStart()), MediaItemDO::getBroadcastingDate, media.getYearOfProductionStart())
                        .lt(StringUtils.isNotBlank(endYear), MediaItemDO::getBroadcastingDate, endYear)
                        .ge(media.getCreatDateStart() != null, MediaItemDO::getCreateDate, media.getCreatDateStart())
                        .lt(media.getCreatDateEnd() != null, MediaItemDO::getCreateDate, media.getCreatDateEnd())
                        .eq(StringUtils.isNotBlank(media.getSubType()), MediaItemDO::getSubType, media.getSubType())
                        .eq(media.getStatus() != null, MediaItemDO::getStatus, media.getStatus())
                        .eq(MediaItemDO::getValid, 1)

        );

        return pageResult;
    }


    @PostMapping("getNews")
    @ApiOperation("获取新闻")
    public R getByPid(@RequestBody NamesDTO namesDTO) {
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (CollectionUtil.isEmpty(namesDTO.getNames())) {
            return R.success(Collections.emptyList());
        }

        List<MediaItemDO> mediaItemDOS = mediaItemMapper.selectList(
                Wrappers.lambdaQuery(MediaItemDO.class).in(MediaItemDO::getProjectName, namesDTO.getNames())
        );

        if (CollectionUtil.isEmpty(mediaItemDOS)) {
            return R.success(Collections.emptyList());
        }

        List<MediaRelateDO> mediaRelateDOS = mediaRelateMapper.selectList(Wrappers.lambdaQuery(MediaRelateDO.class)
                .in(MediaRelateDO::getPid, mediaItemDOS.stream().map(MediaItemDO::getId).collect(Collectors.toList())));


        List<MediaRelateDTO> resultList = mediaRelateDOS.stream()
                .sorted(Comparator.comparingInt(MediaRelateDO::getSor))
                .filter(t -> Objects.equals(t.getType(), "新闻"))
                .map(i -> {
                    MediaRelateDTO t = BeanUtils.transform(MediaRelateDTO.class, i);
                    t.setTmpUrl(baseUrl + i.getUrl());
                    return t;
                }).collect(Collectors.toList());
        return R.success(resultList);
    }


    @GetMapping("getByPid")
    @ApiOperation("根据Pid获取详情")
    public R getByPid(Long pid) {

        MediaItemDO mediaItemDO = mediaItemMapper.selectOne(
                Wrappers.lambdaQuery(MediaItemDO.class).eq(MediaItemDO::getPid, pid)
        );
        if (mediaItemDO == null) {
            return R.success(mediaItemDO);
        }

        List<MediaRelateDO> mediaRelateDOS = mediaRelateMapper.selectList(Wrappers.lambdaQuery(MediaRelateDO.class)
                .in(MediaRelateDO::getPid, Arrays.asList(mediaItemDO.getId())));
        Map<Long, List<MediaRelateDO>> mediaRelateMap = mediaRelateDOS.stream().collect(Collectors.groupingBy(MediaRelateDO::getPid));

        MediaItemDTO transform = BeanUtils.transform(MediaItemDTO.class, mediaItemDO);
        List<MediaRelateDO> mediaRelateList = mediaRelateMap.getOrDefault(mediaItemDO.getId(), new ArrayList<>());

        transform.setStillsList(mediaRelateList.stream()
                .sorted(Comparator.comparingInt(MediaRelateDO::getSor))
                .filter(t -> Objects.equals(t.getType(), "剧照"))
                .map(i -> {
                    MediaRelateDTO t = BeanUtils.transform(MediaRelateDTO.class, i);
                    t.setTmpUrl(baseUrl + i.getUrl());
                    return t;
                }).collect(Collectors.toList()));

        transform.setPosterList(mediaRelateList.stream()
                .sorted(Comparator.comparingInt(MediaRelateDO::getSor))
                .filter(t -> Objects.equals(t.getType(), "海报"))
                .map(i -> {
                    MediaRelateDTO t = BeanUtils.transform(MediaRelateDTO.class, i);
                    t.setTmpUrl(baseUrl + i.getUrl());
                    return t;
                }).collect(Collectors.toList()));

        transform.setTrailersList(mediaRelateList.stream()
                .sorted(Comparator.comparingInt(MediaRelateDO::getSor))
                .filter(t -> Objects.equals(t.getType(), "预告片") || Objects.equals(t.getType(), "片段") || Objects.equals(t.getType(), "花絮"))
                .map(i -> {
                    MediaRelateDTO t = BeanUtils.transform(MediaRelateDTO.class, i);
                    t.setTmpUrl(baseUrl + i.getUrl());
                    return t;
                }).collect(Collectors.toList()));


        transform.setPosterList(mediaRelateList.stream()
                .sorted(Comparator.comparingInt(MediaRelateDO::getSor))
                .filter(t -> Objects.equals(t.getType(), "新闻"))
                .map(i -> {
                    MediaRelateDTO t = BeanUtils.transform(MediaRelateDTO.class, i);
                    t.setTmpUrl(baseUrl + i.getUrl());
                    return t;
                }).collect(Collectors.toList()));

        transform.setMainPicUrl(baseUrl + transform.getMainPic());

        return R.success(transform);
    }

    @PostMapping("update")
    @ApiOperation("更新")
    public R update(@RequestBody MediaItemUpdateDTO media) {


        List<MediaItemDTO> list = new ArrayList<>();
        if (media.getRecord1() != null && media.getRecord1().getId() != null) {
            list.add(media.getRecord1());
        }
        if (media.getRecord2() != null) {
            MediaItemDTO record2 = media.getRecord2();
            record2.setPid(media.getRecord1().getId());
            list.add(record2);
        }
        list.forEach(it -> {
            MediaItemDO transform = BeanUtils.transform(MediaItemDO.class, it);
            if (StringUtils.isNotBlank(transform.getMainPic())) {
                transform.setMainPic(transform.getMainPic().replaceAll("https://interlib.s3.ap-southeast-1.amazonaws.com/", ""));
            }

            if (transform.getId() != null) {
                mediaItemMapper.updateById(transform);
            } else if (transform.getId() == null) {
                mediaItemMapper.insert(transform);
            }
            if (CollectionUtil.isNotEmpty(it.getPosterList())) {
                for (int i = 0; i < it.getPosterList().size(); i++) {
                    MediaRelateDTO mediaRelateDTO = it.getPosterList().get(i);
                    mediaRelateDTO.setSor(i);
                    mediaRelateMapper.updateById(BeanUtils.transform(MediaRelateDO.class, mediaRelateDTO));
                }
            }
            if (CollectionUtil.isNotEmpty(it.getStillsList())) {
                for (int i = 0; i < it.getStillsList().size(); i++) {
                    MediaRelateDTO mediaRelateDTO = it.getStillsList().get(i);
                    mediaRelateDTO.setSor(i);
                    mediaRelateMapper.updateById(BeanUtils.transform(MediaRelateDO.class, mediaRelateDTO));
                }
            }
            if (CollectionUtil.isNotEmpty(it.getTrailersList())) {
                for (int i = 0; i < it.getTrailersList().size(); i++) {
                    MediaRelateDTO mediaRelateDTO = it.getTrailersList().get(i);
                    mediaRelateDTO.setSor(i);
                    mediaRelateMapper.updateById(BeanUtils.transform(MediaRelateDO.class, mediaRelateDTO));
                }
            }
        });


        return R.success(true);
    }

    @Login
    @PostMapping("push")
    @ApiOperation("推送")
    public R push(@RequestBody IdsDTO idList) {
        if (CollectionUtil.isEmpty(idList.getIdList())) {
            throw new ApiException(ApiExceptionEnum.EXIST_NULL_CODE_ERROR);
        }

//        String collect = mediaItemDOS.stream().filter(it -> Objects.equals(it.getStatus(), 1)).map(MediaItemDO::getProjectName).collect(Collectors.joining(","));
//        if (StringUtils.isNotBlank(collect)) {
//            throw new ApiException(ApiExceptionEnum.EXIST_NULL_CODE_ERROR.getCode(), collect + " 已经推送过了！");
//        }

        log.info("param {}", JSON.toJSONString(idList));

        String param = JSON.toJSONString(idList);

        String result = HttpUtil.post("http://localhost:5000/push", param);

        log.info("result {}", result);


        JSONObject resultJSON = JSON.parseObject(result);
        log.info("idList {} result {}", JSON.toJSONString(idList), resultJSON);

        if ("pro".equals(idList.getType())) {
            MediaItemDO mediaItemDO = new MediaItemDO();
            mediaItemDO.setStatus(1);
            mediaItemMapper.update(mediaItemDO,
                    Wrappers.lambdaQuery(MediaItemDO.class).in(MediaItemDO::getId, idList.getIdList())
            );
        }
        if (!Integer.valueOf("200").equals(resultJSON.getInteger("code"))) {
            throw new ApiException(ApiExceptionEnum.DEFAULT_ERROR.getCode(), resultJSON.getString("message"));
        }
        return R.success(resultJSON.getString("message"));

    }
}

